package com.general.geekbang.myhttpserver;


import java.util.ArrayList;
import java.util.Collection;

/**
 * @description: AntURLPatternsMatcher
 * @author: general
 * @version: 1.0
 * @create: 2021-07-03 18:20
 **/
public class AntURLPatternsMatcher implements URLPatternsMatcher {

    private Matcher matcher;

    private Collection<String> pattern = new ArrayList<>();

    private boolean caseSensitive;

    public AntURLPatternsMatcher(Collection<String> pattern, boolean caseSensitive) {
        if(null == pattern || pattern.isEmpty()){
            throw new IllegalArgumentException("patterns cannot be null");
        }
        this.matcher = new CustomAntMatcher(pattern, caseSensitive);
        this.pattern = pattern;
        this.caseSensitive = caseSensitive;
    }

    @Override
    public boolean matches(Collection<String> urlPatterns, String requestURI) {
        if(null == urlPatterns || urlPatterns.isEmpty()){
            throw new IllegalArgumentException("patterns cannot be null");
        }
        return this.matcher.matches( requestURI);
    }


    private interface Matcher {
        boolean matches(String path);
    }

    private static class CustomAntMatcher implements Matcher {

        private final AntPathMatcher antMatcher;

        private final Collection<String> pattern;

        private CustomAntMatcher(Collection<String> pattern, boolean caseSensitive) {
            this.pattern = pattern;
            this.antMatcher = createMatcher(caseSensitive);
        }

        @Override
        public boolean matches(String path) {
            return this.antMatcher.match(this.pattern, path);
        }


        private static AntPathMatcher createMatcher(boolean caseSensitive) {
            AntPathMatcher matcher = new AntPathMatcher();
            matcher.setTrimTokens(false);
            matcher.setCaseSensitive(caseSensitive);
            return matcher;
        }
    }
}
